package com.lanzhou.yuanfen.lottery;

import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author Administrator
 */
@Component
public class RandomLottery {

    /**
     * String 可以为任意类型 也可以自定义类型
     */
    private Map<String, Integer> keyChanceMap = new HashMap<>();

    /*static {
        keyChanceMap.put("aaa", 500);
        keyChanceMap.put("bbb", 1500);
        keyChanceMap.put("ccc", 2000);
        keyChanceMap.put("ddd", 3000);
        keyChanceMap.put("eee", 3000);
    }*/

    /**
     * 开始方法
     *
     * @param boxId 箱子ID, 其实控制的是类型
     * @return 抽取到的奖品
     */
    public String lottery(String boxId) {
        loadPrizePool(boxId);
        List<String> list = new ArrayList<>();
        String item = null;
        for (int i = 0; i < 10000; i++) {
            item = chanceSelect(keyChanceMap);
            list.add(item);
        }
        Random rand = new Random();
        int num = rand.nextInt(10000);
        return list.get(num);
    }

    /**
     * 加载奖池
     *
     * @param boxId 礼品类型/奖品盒子ID
     * @return
     */
    private void loadPrizePool(String boxId) {
        // TODO 获取数据库奖品信息加载到奖池中
    }

    /**
     * 分配权重
     *
     * @param keyChanceMap
     * @return
     */
    public static String chanceSelect(Map<String, Integer> keyChanceMap) {
        if (keyChanceMap == null || keyChanceMap.size() == 0) {
            return null;
        }
        Integer sum = keyChanceMap.values().parallelStream().reduce(0, (a, b) -> a + b);
        // 从1开始
        Integer rand = new Random().nextInt(sum) + 1;
        for (Map.Entry<String, Integer> entry : keyChanceMap.entrySet()) {
            rand -= entry.getValue();
            // 选中
            if (rand <= 0) {
                return entry.getKey();
            }
        }
        return null;
    }


    public Map<String, Integer> getKeyChanceMap() {
        return keyChanceMap;
    }

    public void setKeyChanceMap(Map<String, Integer> keyChanceMap) {
        this.keyChanceMap = keyChanceMap;
    }
}
